package com.ds.dsm.view.config.form;

import com.ds.common.JDSException;
import com.ds.config.TreeListResultModel;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.bean.ApiClassConfig;
import com.ds.esd.custom.bean.MethodConfig;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.form.CustomFormViewBean;
import com.ds.esd.dsm.DSMFactory;
import com.ds.esd.dsm.view.ViewEntityConfig;
import com.ds.esd.dsm.view.field.FieldModuleConfig;
import com.ds.esd.util.TreePageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/dsm/view/config/form/module/")
public class ViewFormModulesService {

    @RequestMapping(method = RequestMethod.POST, value = "ChildModuleTree")
    @APIEventAnnotation(bindMenu = CustomMenuItem.loadChild)
    @ResponseBody
    public TreeListResultModel<List<FormNavTree>> getChildModuleTree(String domainId, String sourceClassName, String methodName, String viewInstId) {
        TreeListResultModel<List<FormNavTree>> result = new TreeListResultModel<>();
        try {
            ViewEntityConfig classConfig = DSMFactory.getInstance().getViewManager().getViewEntityConfig(sourceClassName,  viewInstId);
            ApiClassConfig customESDClassAPIBean = classConfig.getSourceConfig();
            MethodConfig methodAPIBean = customESDClassAPIBean.getMethodByName(methodName);
            CustomFormViewBean customFormViewBean = (CustomFormViewBean) methodAPIBean.getView();
            List<String> fieldNames = customFormViewBean.getModuleFieldNames();
            List<FieldModuleConfig> fields = new ArrayList<>();
            for (String fieldname : fieldNames) {
                Object object = customFormViewBean.getFieldConfigMap().get(fieldname);
                if (object instanceof FieldModuleConfig) {
                    FieldModuleConfig fieldModuleConfig = (FieldModuleConfig) customFormViewBean.getFieldConfigMap().get(fieldname);
                    if (fieldModuleConfig != null && !fieldModuleConfig.getColHidden()) {
                        fieldModuleConfig.setEntityClassName(customFormViewBean.getViewClassName());
                        fields.add(fieldModuleConfig);
                    }
                }
            }
            result = TreePageUtil.getTreeList(fields, FormNavTree.class);

        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }

}
